/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import store from '@/vuex/store';
import router from '@/router/index'
import {serialize} from '@/utils/util'
import {getToken} from '@/utils/auth'
import {Message} from 'element-ui'
import qs from 'qs';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
export const clientAuthorization = 'Basic aW52ZXN0LXNkOmludmVzdC1zZF9zZWNyZXQ='; // 客户端id

axios.defaults.withCredentials = true;
axios.defaults.timeout = 10000;
//返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
  showSpinner: false
});
//HTTPrequest拦截
axios.interceptors.request.use(config => {
  NProgress.start() // start progress bar
  const meta = (config.meta || {});
  const isToken = meta.isToken === false;
  if(config.url.indexOf("outApi") > -1) {
    // 满天星接口特用header
    config.headers['Authorization'] = 'e4e3e907ff18b1853ea61693a3328146';
  } else {
    //config.headers['Authorization'] = clientAuthorization;
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    if (getToken() && !isToken) {
      config.headers['Authorization'] = 'bearer ' + getToken() // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
    }
  }
  
  //headers中配置serialize为true开启序列化
  if (config.method === 'post' && meta.isSerialize === true) {
    config.data = serialize(config.data);
  }
  store.state.loading = true
  return config
}, error => {
  return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(res => {
  setTimeout(() => {
    store.state.loading = false
}, 300);
  NProgress.done();
  if(res.config.headers['LogApi']){
    return res;
  }
  const status = res.data.code || 200
  // const statusWhiteList = website.statusWhiteList || [];
  const message = res.data.msg || '未知错误';
  // //如果在白名单里则自行catch逻辑处理
  // if (statusWhiteList.includes(status)) return Promise.reject(res);
  //如果是401则跳转到登录页面
  if (status === 401) store.dispatch('FedLogOut').then(() => router.push({path: '/login'}));
  // 如果请求为非200否者默认统一处理
  // if (status !== 200) {
  //   Message({
  //     message: message,
  //     type: 'error'
  //   })
  //   return Promise.reject(new Error(message))
  // }
  return res;
}, error => {
  NProgress.done();
  setTimeout(() => {
    store.state.loading = false
}, 300);
  return Promise.reject(new Error(error));
})

export default axios;
//基地址
export let base = process.env.BUSINESS_BASE_URL

//通用方法
export const POST = (url, params, baseUrl=base) => {
  return axios.post(`${baseUrl}${url}`, qs.stringify(params)).then(res => res.data)
}
export const GET = (url, params, baseUrl=base) => {
  return axios.get(`${baseUrl}${url}`, {
    params: params,
  }).then(res => res.data)
}
export const PUT = (url, params, baseUrl=base) => {
  return axios.put(`${baseUrl}${url}`, params).then(res => res.data).catch((error) => error)
}
export const DELETE = (url, params, baseUrl=base) => {
  return axios.delete(`${baseUrl}${url}`, {
    params: params
  }).then(res => res.data).catch((error) => error)
}
export const PATCH = (url, params, baseUrl=base) => {
  return axios.patch(`${baseUrl}${url}`, params).then(res => res.data).catch((error) => error)
}

